package com.jfsnpm.common;




import org.apache.commons.lang.StringUtils;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.JFinal;
import com.jfsnpm.authority.AuthorityCheck;
import com.jfsnpm.plugin.bjui.BjuiRender;

public class GlobalInterceptor implements Interceptor {
	public void intercept(Invocation ai) {
		new AuthorityCheck();
		//是否登陆
		if(!AuthorityCheck.isLogin(ai.getController())){
			if(ai.getActionKey().equals("/Index/main")){
				ai.getController().redirect("/Login/login");
			}else{
				ai.getController().render(BjuiRender.timeout());
			}
			return;
		}
		//路径权限判断
		if(!AuthorityCheck.getPathAuthoriy(ai)){
			//ai.getController().renderError(401);
			ai.getController().render(BjuiRender.code(401));
			return;
		}
		ai.getController().setAttr("userid", ai.getController().getSessionAttr("userid"));
		ai.getController().setAttr("username", ai.getController().getSessionAttr("username"));
		if(!JFinal.me().getConstants().getDevMode()){
			//异常集中返回json
			try {
				ai.invoke();
			} catch (RuntimeException e) {
				//最多处理10次嵌套查询原始出错信息
				Throwable t = e.getCause();
				for (int i = 0; i < 10; i++) {
					if(StringUtils.isNotBlank(t.getMessage())){
						ai.getController().render(BjuiRender.error(t.getMessage()));
						return;
					}
					t = t.getCause();
				}
				throw new RuntimeException(e);
			} catch (Exception e) {
				throw new RuntimeException(e);
			}
		}else{
			ai.invoke();
		}
	}
	
}
